package com.netty.chapter01.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author zjiajia
 * @date 2024/7/8 11:00
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 客户端连接成功之后，会出发这个事件，只会出发一次
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, netty".getBytes()));
    }

    /**
     * 接受服务器响应时触发这个事件
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;

        byte[] bytes = new byte[byteBuf.readableBytes()];
        // 读取数据
        byteBuf.readBytes(bytes);
        String response = new String(bytes, "utf-8");
        System.out.println("response data is : " + response);

    }
}
